<?php

use Core\ResourceController;
use Models\Address;

class AddressController extends ResourceController
{
	public function index()
	{

		$addresses = Address::where('user_id', $this->session->authUser['id'])
			->with(['province_region', 'city_region', 'area_region'])
			->get();

		return $this->success([
			'addresses' => $addresses,
		]);
	}

	// 保存地址
	public function save()
	{
		$this->load->library('form_validation');
		$this->form_validation->set_rules('accept_name', '真实姓名', 'required|max_length[20]')
		->set_rules('province', '省份', 'required|exist[regions.id]')
		->set_rules('city', '城市', 'required|exist[regions.id]')
		->set_rules('area', '地区', 'exist[regions.id]')
		->set_rules('address', '详细地址', 'required|max_length[1000]')
		->set_rules('mobile', '手机号', 'required|numeric')
		->set_rules('is_default', '是否默认地址', 'in_list[0,1]');
		if ($this->form_validation->run()) {
			$address = new Address();
			if ($this->input->post('id')) {
				$address = $address->find($this->input->post('id'));
				if (!$address) {
					return $this->notFoundResponse();
				}
			}

			$address->load($this->input->post());

			if ($this->input->post('id')) {
				$result = $address->update();
			} else {
				$address['user_id'] = $this->session->authUser['id'];
				$result = $address->add();
			}
			if ($result) {
				if ($address['is_default'] == 1) {
					Address::where('is_default', 1)
					->where('id !=', $address['id'])
					->updateAll([
						'is_default' => 0
					]);
				}
				$address->find($address['id']);
			} else {
				log_message('error', $this->db->error());
			}

			$address['province_region'] = $address->province_region();
			$address['city_region'] = $address->city_region();
			$address['area_region'] = $address->area_region();

			return $this->success($address);
		} else {
			return $this->validateError($this->form_validation->error_string());
		}
	}

	// 设为默认地址
	public function set_default()
	{
		if (!$this->input->post('id')) {
			return ;
		}
		$address = (new Address)->find($this->input->post('id'));
		if (!$address) {
			return $this->notFoundResponse();
		}
		$address['is_default'] = 1;
		$address->update();

		Address::where('is_default', 1)
			->where('id !=', $address['id'])
			->updateAll(['is_default' => 0]);

		return $this->success();
	}

	public function delete()
	{
		if (!$this->input->post('id')) {
			return;
		}

		$address = (new Address)->where([
			'user_id' => $this->session->authUser['id'],
			'id' => $this->input->post('id')
		])->get_one();
		if (!$address) {
			return $this->notFoundResponse();
		}

		$address->delete();

		return $this->success();
	}
}
